package purchase.wf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.xpath.DefaultXPath;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.Token;


public class JbpmProcessImagePositionServlet implements Servlet {

	private static Log log = LogFactory.getLog(JbpmProcessImagePositionServlet.class);
	
	public ServletConfig getServletConfig() {
		return this.getServletConfig();
	}

	public String getServletInfo() {
		return this.getServletInfo();
	}

	public void init(ServletConfig servletConfig) throws ServletException {
		log.info("JbpmProcessImagePositionServlet init......");
	}
	
	public void destroy() {
		log.info("JbpmProcessImagePositionServlet destroy......");
	}

	/**
	 * 编码设置
	 * @param request
	 * @param response
	 */
	private void setReqRespEncoding(ServletRequest request,
			ServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	}

	private void getNodePosition(Element gpdRootElement, String nodeName,
			List<Map<String,String>> mapList,boolean isCurrentTaskToken) {
		String xpathStr = "//node[@name='"+nodeName+"']";
		XPath xpath = new DefaultXPath(xpathStr);
		Element currentXmlNode = (Element)xpath.selectSingleNode(gpdRootElement);
		
		String x = currentXmlNode.attributeValue("x");
		String y = currentXmlNode.attributeValue("y");
		String w = currentXmlNode.attributeValue("width");
		String h = currentXmlNode.attributeValue("height");
		
		Map<String,String> map = new HashMap<String,String>();
		map.put("x", x);
		map.put("y", y);
		map.put("w", w);
		map.put("h", h);
		if (isCurrentTaskToken) {
			map.put("isCurrentTaskToken", "yes");
		} else {
			map.put("isCurrentTaskToken", "no");
		}
		
		mapList.add(map);
	}
	
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		setReqRespEncoding(request, response);

		String tokenId = request.getParameter("tokenId");
		
		JbpmContext jbpmContext = null;
		try {
			jbpmContext = JbpmConfiguration.getInstance().createJbpmContext();
			Token currentToken = jbpmContext.getToken(Long.parseLong(tokenId));
			
			ProcessDefinition processDefinition = 
				currentToken.getProcessInstance().getProcessDefinition();
			
			byte[] gpdFileBytes = processDefinition.getFileDefinition().getBytes("gpd.xml");
			//将gpd.xml定位文件的二进制内容解析成xml结构化数据
			Element gpdRootElement = DocumentHelper.parseText(
					new String(gpdFileBytes)).getRootElement();
			
			//log.info(gpdRootElement.asXML());
			
			//process image width height
			String width = gpdRootElement.attributeValue("width");
			String height = gpdRootElement.attributeValue("height");
			long processDefinitionId = processDefinition.getId();
			
			//save node position
			List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
			
			Token rootToken = currentToken.getParent();
			if (rootToken == null) {
				String nodeName = currentToken.getNode().getName();
				this.getNodePosition(gpdRootElement, nodeName, mapList,true);
				
			} else {
				Map children = rootToken.getChildren();
				
				if (children != null) {
					Collection<Token> allToken = new ArrayList<Token>();
					Collection<Token> childTokens = children.values();
					allToken.addAll(childTokens);
					allToken.add(rootToken);
					
					for (Iterator<Token> ite = allToken.iterator();ite.hasNext();) {
						boolean isCurrentTaskToken = false;
						Token childToken = ite.next();
						String nodeName = childToken.getNode().getName();
						
						if (nodeName.equals(currentToken.getNode().getName())) {
							isCurrentTaskToken = true;
						}
						
						this.getNodePosition(gpdRootElement, nodeName, mapList,isCurrentTaskToken);
					}
				}
			}
			
			request.setAttribute("width", width);
			request.setAttribute("height", height);
			request.setAttribute("processDefinitionId", processDefinitionId+"");
			request.setAttribute("mapList", mapList);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jbpmContext.close();
		}
		
		// 跳转
		request.getRequestDispatcher("/purchase/processImage.jsp").forward(request, response);
	}

}
